/**
 * Copyright (c) 2015 Baidu. All Rights Reserved.
 *
 * @file 用于发起http请求
 * @author yuanguozheng
 */
var request = require('request');
var querystring = require('querystring');
var ResponseModel = require('../models/response_model');

/**
 * 发起请求
 *
 * @param {Object} requestModel 请求实体
 * @param {Function} callback 回调函数
 */
function doReq(requestModel, callback) {
    if (requestModel == null || callback == null) {
        return;
    }
    var options = optionMaker(requestModel);
    request(options, function (err, res, body) {
            if (!err) {
                var resModel = new ResponseModel();
                resModel.code = res.statusCode;
                if (res.statusCode === 200) {
                    resModel.headers = res.headers;
                    resModel.body = body;
                }
                callback(resModel);
            } else {
                console.error('请求错误');
                callback(null);
            }
        }
    );
}

/**
 * 用于为request构建option
 *
 * @param {Object} requestModel 请求实体
 * @return {Object} 所需的option
 */
function optionMaker(requestModel) {
    var option;
    option = {
        uri: requestModel.url,
        method: requestModel.method,
        headers: requestModel.headers
    };
    if (option.method.toUpperCase() === 'GET') {
        option.uri += '?' + stringParamsParser(requestModel.params);
    } else if (option.method.toUpperCase() === 'POST') {
        option.form = requestModel.params;
    }
    return option;
}

/**
 * 用于将对象转为字符串参数
 *
 * @param {Object} params 参数对象
 * @return {string} 字符串参数
 */
function stringParamsParser(params) {
    return querystring.stringify(params);
}

module.exports = {
    doReq: doReq
};